package com.aliang.frame.service.impl;

import com.aliang.frame.domain.*;
import com.aliang.frame.domain.Dept;
import com.aliang.frame.repository.DeptMapper;
import com.aliang.frame.service.DeptService;
import com.aliang.frame.service.enums.ActionEnum;
import com.aliang.frame.utility.ModelMapperSingle;
import com.aliang.frame.viewmodel.admin.dept.DeptPageRequestVM;
import com.aliang.frame.viewmodel.admin.dept.DeptPageResponseVM;
import com.aliang.frame.viewmodel.admin.dept.DeptRequestVM;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class DeptServiceImpl extends BaseServiceImpl<Dept> implements DeptService {

    protected final static ModelMapper modelMapper = ModelMapperSingle.Instance();
    private final DeptMapper deptMapper;

    public DeptServiceImpl(DeptMapper deptMapper) {
        super(deptMapper);
        this.deptMapper = deptMapper;
    }

    @Override
    public List<Dept> page(DeptPageRequestVM requestVM) {
        return deptMapper.selectList(requestVM);
    }

    @Override
    public void edit(DeptRequestVM model, User user) {
        ActionEnum actionEnum = (model.getId() == null) ? ActionEnum.ADD : ActionEnum.UPDATE;
        Dept dept = null;
        Date now = new Date();

        // 如果是新增操作
        if (actionEnum == ActionEnum.ADD) {
            dept = modelMapper.map(model, Dept.class);
            // 设置时间戳、状态、创建人和更新人等信息
            dept.setCreateTime(now);
            dept.setUpdateTime(now);
            dept.setDeleted(false);  // 默认不删除
            dept.setStatus(true);    // 设置status为true
            dept.setCreateBy(user.getId());  // 设置创建人
            dept.setUpdateBy(user.getId());  // 设置更新人

            deptMapper.insertSelective(dept);
        } else {
            // 如果是更新操作
            dept = deptMapper.selectByPrimaryKey(model.getId());
            if (dept != null) {
                modelMapper.map(model, dept);
                dept.setUpdateTime(now);
                dept.setUpdateBy(user.getId());  // 设置更新人

                deptMapper.updateByPrimaryKeySelective(dept);
            }
        }

        // 将部门ID设置到VM中
        model.setId(dept != null ? dept.getId() : null);
    }


    @Override
    public DeptPageResponseVM deptToVM(Integer id) {
        Dept dept = deptMapper.selectByPrimaryKey(id);
        if (dept == null) {
            return null;
        }
        DeptPageResponseVM vm = modelMapper.map(dept, DeptPageResponseVM.class);
        return vm;
    }

    @Override
    public List<Dept> selectByCurrentUser(Integer deptId) {
        return deptMapper.selectByCurrentUser(deptId);
    }

    @Override
    public List<Dept> selectAllDept() {
        return deptMapper.selectAllDept();
    }
}
